{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Working With the Pythonnet Library\n",
    "\n",
    "## Introduction\n",
    "\n",
    "In this tutorial, we are going begin our exploration of the Python for .NET (`pythonnet`) package, a powerful tool that allows us to access the CLR from Python. To fully understand this topic, we will have to give you some background and help you understand why it was developed.\n",
    "\n",
    "Additionally, throughout this process, I want you to keep a couple of ideas in mind:\n",
    "\n",
    "1. How can we use programs and objects written in other lanaguages?\n",
    "2. If we could use programs from other langauges, what sort of rules would we need to define?\n",
    "3. How would the process of taking one object, written in one language, and using it in another language?\n",
    "\n",
    "## What is Pythonnet?\n",
    "\n",
    "Coming straight from the source, the `pythonnet` library is defined as follows:\n",
    "\n",
    "*Python for .NET (pythonnet) is a package that gives Python programmers nearly seamless integration with the .NET 4.0+ Common Language Runtime (CLR) on Windows and Mono runtime on Linux and OSX. Python for .NET provides a powerful application scripting tool for .NET developers. Using this package you can script .NET applications or build entire applications in Python, using .NET services and components written in any language that targets the CLR (C#, VB.NET, F#, C++/CLI).*\n",
    "\n",
    "In a concise summary, the `pythonnet` package gives us access to the CLR environment on Windows. Having access to this environment allows us to access the .Net framework and it's components like window forms, and the excel interop library.\n",
    "\n",
    "Hopefully, after reading that definition you started to ask some more questions. Well, let's start going through some of your questions.\n",
    "\n",
    "## What is the Common Language Runtime (CLR)?\n",
    "\n",
    "Againg, coming straight from the source, `CLR` is as defined as follows:\n",
    "\n",
    "*The .NET Framework provides a run-time environment called the common language runtime, which runs the code and provides services that make the development process easier.\n",
    "\n",
    "Compilers and tools expose the common language runtime's functionality and enable you to write code that benefits from this managed execution environment. Code that you develop with a language compiler that targets the runtime is called managed code; it benefits from features such as cross-language integration, cross-language exception handling, enhanced security, versioning and deployment support, a simplified model for component interaction, and debugging and profiling services.*\n",
    "\n",
    "In essence, CLR helps manage the execution of .NET programs, regardless of the .NET language they were written in. Additionally, CLR implements the Virtual Execution System which is defined under the Common Langauge Infastructure (CLI).\n",
    "\n",
    "## What is the Common Language Infastructure (CLI)?\n",
    "\n",
    "CLI can be defined as follows:\n",
    "\n",
    "*The Common Language Infrastructure (CLI) is an open specification (technical standard) developed by Microsoft and standardized by ISO and Ecma that describes executable code and a runtime environment that allows multiple high-level languages to be used on different computer platforms without being rewritten for specific architectures. This implies it is platform agnostic.*\n",
    "\n",
    "The CLI defines four specifications that make the CLR possible:\n",
    "\n",
    "1. The Common Type System (CTS)\n",
    "    - A set of data types and operations that are shared by all CTS-compliant programming languages.\n",
    "2. The Metadata\n",
    "    - Information about program structure is language-agnostic, so that it can be referenced between languages and tools, making it easy to work with code written in a language the developer is not using.\n",
    "3. The Common Language Specification (CLS)\n",
    "    - A set of base rules to which any language targeting the CLI should conform in order to interoperate with other CLS-compliant languages. The CLS rules define a subset of the Common Type System.\n",
    "4. The Virtual Execution System (VES)\n",
    "    - The VES loads and executes CLI-compatible programs, using the metadata to combine separately generated pieces of code at runtime.\n",
    "    \n",
    "All compatible languages compile to Common Intermediate Language (CIL), which is an intermediate language that is abstracted from the platform hardware. When the code is executed, the platform-specific VES will compile the CIL to the machine language according to the specific hardware and operating system.\n",
    "\n",
    "\n",
    "## What are the benefits of the Common Lanaguage Runtime Environment?\n",
    "\n",
    "1. Performance improvements.\n",
    "2. The ability to easily use components developed in other languages.\n",
    "3. Extensible types provided by a class library.\n",
    "4. Language features such as inheritance, interfaces, and overloading for object-oriented programming.\n",
    "5. Support for explicit free threading that allows creation of multithreaded, scalable applications.\n",
    "6. Support for structured exception handling.\n",
    "7. Support for custom attributes.\n",
    "8. Garbage collection.\n",
    "9. Use of delegates instead of function pointers for increased type safety and security. For more information about delegates, see Common Type System.\n",
    "\n",
    "\n",
    "## How will we use Pythonnet in this tutorial?\n",
    "\n",
    "In this tutorial, we will keep things simple and work with some of the built in system libraries found in the .Net Framework. More specifically, we will work with the `System.Forms` library and go over common things we may need to do in the library.\n",
    "\n",
    "With all of that being said, let's get coding!\n",
    "\n",
    "***\n",
    "\n",
    "## Installing Pythonnet\n",
    "\n",
    "To install `pythonnet` on your system, run the following command:\n",
    "\n",
    "`pip install pythonnet`\n",
    "\n",
    "After that you can import the libary by writing the following:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "# import the CLR library\n",
    "import clr"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Importing Modules and Loading Assemblies\n",
    "\n",
    "After you've imported the `clr` library you can begin to import CLR Namespaces and Types. For CLR namespaces, importing them is just like importing a normal python package.\n",
    "\n",
    "`from System import String`\n",
    "\n",
    "or\n",
    "\n",
    "`from System.Collections import *`\n",
    "\n",
    "If the assembly you wish to import from is not currently loaded, no worries simply use the `AddReference` method and load the assembly that way. Here is an example of loading an assembly:\n",
    "\n",
    "`import clr`\n",
    "`clr.AddReference('System.Windows.Forms')`\n",
    "\n",
    "Once, you've added the reference you can begin to import Types just like up above.\n",
    "\n",
    "`from System.Windows.Forms import Form`\n",
    "\n",
    "This will load the `Form` Type into Python.\n",
    "\n",
    "Now that we know how to import modules and load assemblies we can move on to the next section, Generics.\n",
    "\n",
    "\n",
    "## Generics\n",
    "Because we are now able to access the world of .Net we get access to a new arsenal of tools that we can use. One of those tools are called `Generics`. A `Generic`, in simple terms, allow for the idea of something called Type Parameters. A Type Parameter is just a way of building a class or defining a method in such a way that it delays the specification of one's type until the class is instantiated or the method is called by the client code.\n",
    "\n",
    "Generic classes and methods combine reusability, type safety and efficiency in a way that their non-generic counterparts cannot.\n",
    "\n",
    "`Pythonnet` supports generic types. A generic type must be bound to create a concrete type before it can be instantiated. Generic types also support the subscript syntax to create bound types.\n",
    "\n",
    "Let's walk through an example and create a `Dictionary` generic."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "For \"myKey1\", the value is myValue1\n",
      "For \"myKey1\", the value is 100\n",
      "For \"myKey3\", the value is 200\n",
      "For \"myKey3\", the type of the value is <class 'int'>\n"
     ]
    }
   ],
   "source": [
    "# add a reference to the System.Collections Assembly\n",
    "clr.AddReference('System.Collections')\n",
    "\n",
    "# generics are usually used with collections, so let's import the 'Dictionary' Generic\n",
    "from System.Collections.Generic import Dictionary\n",
    "\n",
    "# let's also import the different data types we need.\n",
    "from System import *\n",
    "\n",
    "'''\n",
    "    EXAMPLE ONE:\n",
    "    ------------\n",
    "    For the Dictionary Generic, we can specify what Type we want the Key and Value to be.\n",
    "    This helps maintain a little more control over the process. In the first example,\n",
    "    I'm creating a Dictionary Generic that requires the Key to be of Type String and \n",
    "    the Value to be of Type String.\n",
    "'''\n",
    "generic_dict_1 = Dictionary[String, String]()\n",
    "\n",
    "\n",
    "'''\n",
    "    EXAMPLE TWO:\n",
    "    ------------\n",
    "    In the second example, I'm creating a Dictionary Generic that requires the Key to \n",
    "    be of Type String and the Value to be of Type Int32.\n",
    "'''\n",
    "generic_dict_2 = Dictionary[String, Int32]()\n",
    "\n",
    "\n",
    "'''\n",
    "    EXAMPLE THREE:\n",
    "    --------------\n",
    "    In the third example, I'm creating a Dictionary Generic that requires the Key to \n",
    "    be of Type String and the Value to be of Type Type(Object).\n",
    "'''\n",
    "generic_dict_3 = Dictionary[String, Type]()\n",
    "\n",
    "\n",
    "# let's add a value to our Dictionary Generic 2\n",
    "generic_dict_1.Add(\"myKey1\",\"myValue1\")\n",
    "generic_dict_1.Add(\"myKey2\",\"myValue2\")\n",
    "\n",
    "# finally, let's grab a value.\n",
    "print('For \"myKey1\", the value is {}'.format(generic_dict_1[\"myKey1\"]))\n",
    "\n",
    "# let's add a value to our Dictionary Generic 2\n",
    "generic_dict_2.Add(\"myKey1\", 100)\n",
    "generic_dict_2.Add(\"myKey2\", 200)\n",
    "\n",
    "# finally, let's grab a value.\n",
    "print('For \"myKey1\", the value is {}'.format(generic_dict_2[\"myKey1\"]))\n",
    "\n",
    "# here is the neat thing about generics. Even though I'm passing through a string it'll be converted to int.\n",
    "generic_dict_2.Add(\"myKey3\", \"200\")\n",
    "\n",
    "print('For \"myKey3\", the value is {}'.format(generic_dict_2[\"myKey3\"]))\n",
    "print('For \"myKey3\", the type of the value is {}'.format(type(generic_dict_2[\"myKey3\"])))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Fields & Properties\n",
    "\n",
    "Time to introduce another tool, `Fields`. A `Field` is a variable of any type that is declared directly in a class or struct. `Fields` are members of their containing type. Generally, you should use fields only for variables that have private or protected accessibility. \n",
    "\n",
    "Data that your class exposes to client code should be provided through methods, properties and indexers. Fields typically store the data that must be accessible to more than one class method and must be stored for longer than the lifetime of any single method.\n",
    "\n",
    "At this point, we should know what a property is so I won't go over that. You can `get` and `set` fields and properties of CLR objects just as if they were regular attributes."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "My Machine is Called: DESKTOP-MOA8O6M\n"
     ]
    }
   ],
   "source": [
    "# import the Environment Type\n",
    "from System import Environment\n",
    "\n",
    "# the Envrionment Type has a property called `MachineName`\n",
    "my_machine_name = Environment.MachineName\n",
    "\n",
    "# print out my Machine Name\n",
    "print('My Machine is Called: {}'.format(my_machine_name))\n",
    "\n",
    "\n",
    "'''\n",
    "    The Environment Type also has an attribute called `ExitCode` which is just the ExitCode of a process.\n",
    "''' \n",
    "\n",
    "# let's change it to 1 to indicate the process has not completed successfully.\n",
    "Environment.ExitCode = 1\n",
    "\n",
    "# let's change it back to 0, to indicate the process has completed successfully.\n",
    "Environment.ExitCode = 0"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Arrays\n",
    "You can store multiple variables of the same type in an array data structure. You declare an array by specifying the type of its elements.\n",
    "\n",
    "Let's walkthrough declaring `Arrays` in `Pythonnet`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 53,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Here is my Array: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n",
      "Here is the value of my first element: 100\n",
      "Here is my Array: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n",
      "Here is my multi-dimensional Array: [0, 100, 300, 0, 100, 0]\n",
      "Here is my multi-dimensional Array: [[1, 2], [3, 4]]\n"
     ]
    }
   ],
   "source": [
    "# import the Array Type\n",
    "from System import Array\n",
    "\n",
    "'''\n",
    "    Single-Dimension Array.\n",
    "'''\n",
    "\n",
    "# declare a single-dimension array, that will only contain numbers, and contains ten elements that are all 0.\n",
    "array_1 = Array.CreateInstance(int,10)\n",
    "\n",
    "# print your newly created array.\n",
    "print(\"Here is my Array: {}\".format(list(array_1)))\n",
    "\n",
    "# reassign value\n",
    "array_1[0] = 100\n",
    "\n",
    "# grab value from element 1, since we are 0-based.\n",
    "print(\"Here is the value of my first element: {}\".format(array_1[0]))\n",
    "\n",
    "# here is an alternative way to declaring a single \n",
    "array_2 = Array[int](range(10))\n",
    "\n",
    "# print your newly created array.\n",
    "print(\"Here is my Array: {}\".format(list(array_2)))\n",
    "\n",
    "\n",
    "'''\n",
    "    Multi-Dimension Array.\n",
    "\n",
    "'''\n",
    "\n",
    "# declare a multi dimension arrary, that will contain only numbers, and be 2 by 3.\n",
    "multi_array_1 = Array.CreateInstance(int, 2, 3)\n",
    "\n",
    "# assign a value to row 0, column 1\n",
    "multi_array_1[0, 1] = 100\n",
    "\n",
    "# assign a value to row 0, column 1\n",
    "multi_array_1[1, 1] = 100\n",
    "\n",
    "# assign a value to row 0, column 2\n",
    "multi_array_1[0, 2] = 300\n",
    "\n",
    "# print your newly created array.\n",
    "print(\"Here is my multi-dimensional Array: {}\".format(list(multi_array_1)))\n",
    "\n",
    "# here is an alternative method.\n",
    "multi_array_2 = Array[Array[int]]( ( (1, 2), (3, 4) ) )\n",
    "\n",
    "# print your newly created array.\n",
    "print(\"Here is my multi-dimensional Array: {}\".format([list(array) for array in list(multi_array_2)]))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Collections\n",
    "Managed arrays and managed objects that implement the IEnumerable interface can be iterated over using the standard iteration Python idioms."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 58,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "----------\n",
      "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\n",
      "----------\n",
      "clrmodule, Version=2.4.0.0, Culture=neutral, PublicKeyToken=null\n",
      "----------\n",
      "Python.Runtime, Version=2.4.0.0, Culture=neutral, PublicKeyToken=null\n",
      "----------\n",
      "System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\n",
      "----------\n",
      "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\n",
      "----------\n",
      "__CodeGenerator_Assembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null\n",
      "----------\n",
      "e__NativeCall_Assembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null\n",
      "----------\n",
      "System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a\n",
      "----------\n",
      "System.Xml, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\n",
      "----------\n",
      "System.Collections, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a\n"
     ]
    }
   ],
   "source": [
    "# grab the current domain, this belongs under the 'System' namespace.\n",
    "domain = AppDomain.CurrentDomain\n",
    "\n",
    "# get all the assemblies in the domain, this returns a collection that we can loop through.\n",
    "for assembly in domain.GetAssemblies():\n",
    "    \n",
    "    # grab the assembly name, using the GetName() method.\n",
    "    assembly_name = assembly.GetName()\n",
    "    \n",
    "    print('-'*10)\n",
    "    print(assembly_name)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Using Indexers\n",
    "At this point, we've used indexers multiple times, but just to be consistent let's dedicate a section to it. If a managed object implements one or more indexers, you can call the indexer using standard Python indexing syntax."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 63,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Using the key method, I got the value: 100\n",
      "Using the index method, I got the value: 100\n",
      "Using the index method multi, I got the value: 300\n"
     ]
    }
   ],
   "source": [
    "# key method\n",
    "print(\"Using the key method, I got the value: {}\".format(generic_dict_2['myKey1']))\n",
    "\n",
    "# index method\n",
    "print(\"Using the index method, I got the value: {}\".format(array_1[0]))\n",
    "\n",
    "# index method, multi.\n",
    "print(\"Using the index method multi, I got the value: {}\".format(multi_array_1[0,2]))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
